<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends FOX_Controller {

	function __construct ()
	{
		parent::__construct();
		$this->load->model('user_m');
		$this->load->library('form_validation');
	}
	
	public function home()
	{
		if(!$this->auth->is_login())
		{
			redirect(site_url('user/login'));
		}else{
			if($this->auth->is_admins()){
				redirect(site_url(X_URL.'home'));
			}elseif($this->auth->is_shops()){
				redirect(site_url('shop/home'));
			}
		}
	}
	
	private function validate_login_form(){
		$this->form_validation->set_rules('username', '帐号' , 'trim|required|min_length[3]|xss_clean');
		$this->form_validation->set_rules('password', '密码' , 'trim|required|min_length[6]|max_length[18]');
		$this->form_validation->set_message('required', "%s 不能为空！");
		$this->form_validation->set_message('min_length', "%s 最小长度不少于 %s 个字符！");
		$this->form_validation->set_message('max_length', "%s 最大长度不多于 %s 个字符！");
		if ($this->form_validation->run() == FALSE){
			return FALSE;
		}else{
			return TRUE;
		}
	}

	public function login()
	{
		if($this->auth->is_login())
		{
			redirect(site_url('user/home'));
		}
		if($_POST && $this->validate_login_form()){

			$usernames = $this->input->post('username', TRUE);
			if(checkMobile($usernames)){
				$username = $this->user_m->get_username_by_utel($usernames);
                $username = $username['user_name'];
			}elseif(validateEmail($usernames)){
				$username = $this->user_m->get_username_by_uemail($usernames);
			}else{
				$username = $usernames;
			}
			if(!$this->user_m->check_ulock($username)){
				show_message('你的账号涉嫌违规，已被冻结！',site_url('user/login'));
				exit;
			}
			$userpass = $this->input->post('password',TRUE);
			$str = array(
				'user_name' => $username,
				'user_password' => $userpass
			);

			if ($this->user_m->login($str)) {
                // 用户组是否已经禁用
                $uid = $this->session->userdata('user_id');
                $userinfo=$this->user_m->get_user_by_user_id($uid);
                if(!$this->authGroup_m->is_user_group_able($userinfo['user_group'])){
                    $this->user_m->del_user_key_by_user_id($uid);
                    $this->session->unset_userdata('user_id');
                    setcookie('loveme', '', time() - 3600, '/', '', false, true);

                    show_message('用户组已被禁用！',site_url('user/login'));
                    exit;
                }
				$dates = date('Ymd',time());
				$udates = date('Ymd',$userinfo['user_logtime']);
				//更新登陆次数
				$this->user_m->update_ulognum($uid);
				//更新最后登录时间
				$this->user_m->update_user($uid,array('user_logtime'=>time()));
				if($this->config->item('credit_login')>0 && $dates<>$udates){
					$this->user_m->update_credit($uid,$this->config->item('credit_login'));
				}	
				//经纬度
				show_message('恭喜您，成功登陆本站！',site_url('user/home'),1);
				exit;
			}else{
				show_message('抱歉哦，登陆本站失败！',site_url('user/login'));
				exit;
			}
		}
		$data['web_title'] = '登陆 -- '.$this->config->item('site_name');
		$data['top_memu'] = 'login';
		$this->load->view('user/login',$data);
	}


	public function check_username($username)
	{  
		if(!preg_match('/^(?!_)(?!.*?_$)[A-Za-z0-9_]+$/u', $username)){
			$this->form_validation->set_message('check_username', '帐号 必须为数字或者字母组成');
  			return false;
		} else{
			$user=$this->user_m->get_user_by_username($username);
			if(isset($user)){
				$this->form_validation->set_message('check_username', '帐号 已经存在啦');
				return false;
			}else{
				return true;
			}			
		}
	}
	
	public function disabled_username($username)
	{
		$user_arr=explode(',',$this->config->item('disabled_username'));
		$num = 0;
		foreach($user_arr as $k => $v){
			$tmparray = explode($v,$username);
			if(count($tmparray)>1){
				$num = $num+1;				
			}
		}
		if($num>=1){
			$this->form_validation->set_message('disabled_username', '帐号 含不允许的字符 '.$v);
			return false;
		}else{
			return true;
		}		
	}

	public function is_mobile($mobile)
	{  
		if(!checkMobile($mobile)){
			$this->form_validation->set_message('is_mobile', '请输入正确的手机号码');
			return false;
		}else{
			return true;
		}
	}
	

	private function validate_register_form(){
		$this->form_validation->set_rules('username', '帐号' , 'trim|required|min_length[3]|max_length[15]|is_unique[users.username]|callback_check_username|callback_disabled_username|xss_clean');
		$this->form_validation->set_rules('password', '密码' , 'trim|required|min_length[6]|max_length[18]');
		$this->form_validation->set_rules('upassword', '重复密码' , 'trim|required|matches[password]');
		$this->form_validation->set_rules('utel', '手机号' , 'trim|required|min_length[8]|is_unique[users.utel]|callback_is_mobile|max_length[15]|xss_clean');
		$this->form_validation->set_rules('tuijianren', '推荐ID' , 'trim|numeric');
		$this->form_validation->set_message('is_unique', "%s 已存在，请更换！");
		$this->form_validation->set_message('required', "%s 不能为空！");
		$this->form_validation->set_message('min_length', "%s 最小长度不少于 %s 个字符！");
		$this->form_validation->set_message('max_length', "%s 最大长度不多于 %s 个字符！");
		if ($this->form_validation->run() == FALSE){
			return FALSE;
		}else{
			return TRUE;
		}
	}
	
	public function register($tuijianren=0)
	{
		if($this->auth->is_login ())
		{
			redirect(site_url('user/home'));
		}
		if($this->config->item('member_close')=='off'){
			show_message('抱歉，本站已经关闭会员注册功能！',site_url('user/login'));
		}
		
		if(is_numeric($tuijianren) && $tuijianren<>0){
			$_COOKIE['tuiuid'] = $tuijianren;
			set_cookie('tuiuid',$tuijianren,86500);		
		}
		$tuiuid = get_cookie('tuiuid',TRUE);
		if($tuiuid){
			$data['tuijianren'] = $tuiuid;
			$userinfo=$this->user_m->get_user_by_uid($tuiuid);
		}else{
			$data['tuijianren'] = $tuijianren;
		}
		if($_POST && $this->validate_register_form()){
			$password = $this->input->post('password',true);
			$salt =get_salt();
			$str = array(
				'username' => strip_tags($this->input->post('username')),
				'upassword' => password_dohash($password,$salt),
				'salt' => $salt,
				'utel' => $this->input->post('utel',true),
				'uregip' => get_onlineip(),
				'ucredit' => $this->config->item('credit_start'),
				'umoney' => 0,
				'utype' => 1,
				'ugroup' => 1,
				'tuijianren' => $this->input->post('tuijianren'),
				'uregtime' => time(),
				'ulogtime' => time(),
				'ulock' => 0
			);
			if($this->user_m->register($str)){
				$inuid = $this->db->insert_id();
				if($this->config->item('credit_start')>0){
					$mes = array(
						'm_type'=>0,//会员积分加减
						'm_title'=>'会员注册',
						'userid'=>$inuid,
						'send_userid'=>0,
						'm_content' =>'成功注册，系统初始化赠送积分 <span class="text-red">'.$this->config->item('credit_start').' </span>',
						'm_lock'=>0,
						'm_time'=>time(),
					);
					$this->message_m->add_message($mes);
				}
				if($tuiuid && $this->config->item('credit_register')>0){
					$tuserinfo=$this->user_m->get_user_by_uid($inuid);
					$mes = array(
						'm_type'=>0,//会员积分加减
						'm_title'=>'推荐会员',
						'userid'=>$tuiuid,
						'send_userid'=>0,
						'm_content' =>'推荐会员 '.$tuserinfo['username'].' 注册成功，奖励积分 <span class="text-red">'.$this->config->item('credit_register').' </span>',
						'm_lock'=>0,
						'm_time'=>time(),
					);
					$this->message_m->add_message($mes);
					$this->user_m->update_credit($tuiuid,$this->config->item('credit_register'));
				}

				show_message('恭喜，注册会员成功！',site_url('user/login'),1);
			}
		}
		$data['web_title'] = '注册 -- '.$this->config->item('site_name');
		$data['top_memu'] = 'register';
		$this->load->view('user/register',$data);
	}
	
	public function login_box()
	{
		$this->load->view('user/login_box');
	}
	
	public function follow_user()
	{
		if($this->input->is_ajax_request()){
			$userid = $this->input->post('userid', TRUE);
			$type = $this->input->post('type',TRUE);
			$uid = $this->session->userdata('user_id');
			if(!$uid){
				$arr = array ('status'=>0,'msg'=>'只有会员才可以操作','urlbox'=>'user/login_box','title'=>'会员登陆','icon'=>5,'code'=>$this->security->get_csrf_hash());
				echo json_encode($arr);
				exit;
			}else{
				if($uid == $userid){
					$arr = array ('status'=>0,'msg'=>'您无法自己关注自己','icon'=>5,'code'=>$this->security->get_csrf_hash());
					echo json_encode($arr);
					exit;
				}else{
					if($this->follow_m->follows_users_utype_twouid($uid,$userid)){
						$arr = array ('status'=>1,'msg'=>'恭喜，关注会员成功','icon'=>6,'code'=>$this->security->get_csrf_hash());
						echo json_encode($arr);
						exit;
					}
				}				
			}
		}
	}
	
	public function follow_unuser()
	{
		if($this->input->is_ajax_request()){
			$userid = $this->input->post('userid', TRUE);
			$type = $this->input->post('type',TRUE);
			$uid = $this->session->userdata('user_id');
			if(!$uid){
				$arr = array ('status'=>0,'msg'=>'只有会员才可以操作','urlbox'=>'user/login_box','title'=>'会员登陆','icon'=>5,'code'=>$this->security->get_csrf_hash());
				echo json_encode($arr);
				exit;
			}else{
				if($this->follow_m->unfollowusers_utype_twouid($uid,$userid)){
					$arr = array ('status'=>1,'msg'=>'恭喜，取消关注会员成功','icon'=>6,'code'=>$this->security->get_csrf_hash());
					echo json_encode($arr);
					exit;
				}		
			}
		}
	}
	
	public function check_login()
	{
		if($this->input->is_ajax_request()){
			$usernames = $this->input->post('username', TRUE);
			if(checkMobile($usernames)){
				$username = $this->user_m->get_username_by_utel($usernames);
			}elseif(validateEmail($usernames)){
				$username = $this->user_m->get_username_by_uemail($usernames);
			}else{
				$username = $usernames;
			}
			$userpass = $this->input->post('password',TRUE);
			if(!$username){
				$arr = array ('status'=>0,'msg'=>'请填写用户帐号','icon'=>5,'code'=>$this->security->get_csrf_hash());
				echo json_encode($arr);
				exit;
			}
			if(!$userpass){
				$arr = array ('status'=>0,'msg'=>'请填写用户密码','icon'=>5,'code'=>$this->security->get_csrf_hash());
				echo json_encode($arr);
				exit;
			}
			if(!$this->user_m->check_register_username($username)){
				$arr = array ('status'=>0,'msg'=>'抱歉，没有找到此用户','icon'=>5,'code'=>$this->security->get_csrf_hash());
				echo json_encode($arr);
				exit;
			}
			if(!$this->user_m->check_ulock($username)){
				$arr = array ('status'=>0,'msg'=>'你的账号涉嫌违规，已被冻结','icon'=>4,'code'=>$this->security->get_csrf_hash());
				echo json_encode($arr);
				exit;
			}
			$str = array(
				'username' => $username,
				'upassword' => $userpass
			);
			if ($this->user_m->login($str)) {
				$uid = $this->session->userdata('user_id');
				$userid = $this->session->userdata('user_id');
				$ugroup = $this->myredis->get('ugroup');
				$userinfo=$this->user_m->get_user_by_uid($uid);
				$dates = date('Ymd',time());
				$udates = date('Ymd',$userinfo['ulogtime']);
				//更新登陆次数
				$this->user_m->update_ulognum($uid);
				//更新最后登录时间
				$this->user_m->update_user($uid,array('ulogtime'=>time()));
				if($this->config->item('credit_login')>0 && $dates<>$udates){
					$mes = array(
						'm_type'=>0,//会员积分加减
						'm_title'=>'每天登陆',
						'userid'=>$uid,
						'send_userid'=>0,
						'm_content' =>date('Y-m-d',time()).'登陆成功，奖励积分 <span class="text-red">'.$this->config->item('credit_login').' </span>',
						'm_lock'=>0,
						'm_time'=>time(),
					);
					$this->message_m->add_message($mes);
					$this->user_m->update_credit($uid,$this->config->item('credit_login'));
				}
		
				$arr = array ('status'=>1,'msg'=>'恭喜，会员成功登陆','icon'=>6,'code'=>$this->security->get_csrf_hash());
				echo json_encode($arr);
				exit;
			}else{
				$arr = array ('status'=>0,'msg'=>'未知错误','icon'=>4,'code'=>$this->security->get_csrf_hash());
				echo json_encode($arr);
				exit;
			}
		}
	}
	
	public function logout ()
	{
		$this->auth->user_logout();		
		redirect('user/login');
	}
	

	//保存用户信息
	public function sav_user(){
		$user_id = $this->session->userdata('user_id');
		if($this->input->post('user_uname')){
			$data['user_uname'] = $this->input->post('user_uname');
		}
		if($this->input->post('user_birth')){
			$data['user_birth'] = $this->input->post('user_birth');
		}
		$data['user_birth'] = $this->input->post('user_birth');
		$result = $this->user_m->update_user($user_id,$data);
		// pp($result);exit;
		if($result){
			redirect('member/site');
		}else{
			redirect('member/index');
		}
	}
}
